package com.ct.gd.passport.view.exhibition;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ct.gd.passport.R;
import com.ct.gd.passport.common.BaseActivity;
import com.ct.gd.passport.domain.ExhibitionInfoDetail;
import com.ct.gd.passport.view.BundleKeys;
import com.ct.gd.passport.view.widget.CustomHeaderFragment;
import com.up91.common.android.async.ILoading;
import com.up91.common.android.async.SimpleAsyncTask;
import com.up91.common.android.content.SimpleLoader;
import com.up91.common.android.exception.OperationFailException;
import com.up91.common.android.helper.DpPxConvertor;

public class ExhibitionDetailActivity extends BaseActivity implements LoaderCallbacks<Drawable> {
	private FragmentManager			mFgMan;
	private CustomHeaderFragment	mFgHeader;

	private TextView				mTVTitle;
	private ImageView				mIV;
	private TextView				mTVContent;

	@Override
	protected void onBaseCreate(Bundle savedInstanceState) {
		setContentView(R.layout.exhibition_detail);
	}

	@Override
	protected void initViews() {
		mFgMan = getSupportFragmentManager();

		mFgHeader = (CustomHeaderFragment) mFgMan.findFragmentById(R.id.discount_detail_header);
		mFgHeader.setCenterText(R.string.travelAssist_discount);

		mTVTitle = (TextView) findViewById(R.id.tv_discount_detail_title);
		mIV = (ImageView) findViewById(R.id.iv_discount_detail);
		mTVContent = (TextView) findViewById(R.id.tv_discount_detail_content);
	}

	@Override
	protected void onAfterCreate(Bundle savedInstanceStat) {
		int id = getIntent().getIntExtra(BundleKeys.CATALOG_ID, 0);
		new GetDetailTask((ILoading) this, true).execute(id);
	}

	protected void loadPic(String picUrl) {
		load(getCatalogLoader(), picUrl);
	}

	protected ImageLoader getCatalogLoader() {
		LoaderManager loaderManager = getSupportLoaderManager();
		Loader<Drawable> loader = loaderManager.getLoader(0);
		if (null == loader) loader = loaderManager.initLoader(0, null, this);
		return (ImageLoader) loader;
	}

	protected void load(ImageLoader loader, String picUrl) {
		loader.setUrl(picUrl);
		loader.reset();
		loader.startLoading();
	}

	private class GetDetailTask extends SimpleAsyncTask<Integer, Void, ExhibitionInfoDetail> {

		public GetDetailTask(ILoading loading, boolean showLoading) {
			super(loading, showLoading);
		}

		@Override
		protected ExhibitionInfoDetail onLoad(Integer... params) throws Exception {
			return ExhibitionInfoDetail.load(params[0]);
		}

		@Override
		protected void onUI(ExhibitionInfoDetail result) {
			mTVTitle.setText(result.getTitle());
			mTVContent.setText(result.getContent());
			if(null !=  result.getPics() &&  result.getPics().size()>0){
				String picUrl = result.getPics().get(0);
				if (!TextUtils.isEmpty(picUrl)) loadPic(picUrl);
			}
		}

		@Override
		protected void onHandleError(String errorMsg) {
			super.onHandleError(errorMsg);
			ExhibitionDetailActivity.this.finish();
		}

	}

	private static class ImageLoader extends SimpleLoader<Drawable> {
		private String	sCacheDir	= getContext().getCacheDir().getPath();
		private String	remotePath;

		public ImageLoader(Context context, View view) {
			super(context, view);
		}

		public void setUrl(String url) {
			this.remotePath = url;
		}

		@Override
		protected Drawable loadData() throws Exception {
			String fileName = remotePath.substring(remotePath.lastIndexOf("/") + 1);
			String localPath = sCacheDir + File.separator + fileName;

			File file = new File(localPath);
			if (!file.exists()) cacheFromRemote(file);

			return Drawable.createFromPath(file.getPath());
		}

		private void cacheFromRemote(File file) {
			try {
				FileOutputStream fos = new FileOutputStream(file);
				InputStream is = new URL(remotePath).openStream();
				int data = is.read();
				while (-1 != data) {
					fos.write(data);
					data = is.read();
				}
				fos.close();
				is.close();
			} catch (IOException e) {
				throw new OperationFailException("图片加载失败");
			}
		}

	}

	@Override
	public Loader<Drawable> onCreateLoader(int arg0, Bundle arg1) {
		return new ImageLoader(this, mIV);
	}

	@Override
	public void onLoadFinished(Loader<Drawable> arg0, Drawable drawable) {
		if(null == drawable) return;
		mIV.getLayoutParams().height = (int) DpPxConvertor.convertDpToPixel(drawable.getIntrinsicHeight(), this);
		mIV.getLayoutParams().width = (int) DpPxConvertor.convertDpToPixel(drawable.getIntrinsicWidth(), this);
		mIV.setImageDrawable(drawable);
	}

	@Override
	public void onLoaderReset(Loader<Drawable> arg0) {
	}
}
